import FsUtils from "../../utils/fsUtils";
import {FileModel} from "index";
import {Theme} from "@tauri-apps/api/window";
import {open} from "@tauri-apps/api/dialog";

export interface HomeInterFace {
    text: string;
    theme: Theme;
    isEdit: boolean;
    isFullscreen: boolean;
    search: string;
    fileList: FileModel[];
    selectFile: FileModel | null;
    add: () => void;
    onSave: () => void;
    getFileList: () => Promise<FileModel[]>;
    setFileLocalStorage: (fileList: FileModel[]) => void;
    itemClick: (file: FileModel) => void;
    openFile: () => void;
    createFile: (file: FileModel) => FileModel;
    confirmDialog: (message: string) => Promise<boolean>;
    inspectSaveFile: () => Promise<boolean>;
    handlerFullscreen: () => void;
}

export class Home implements HomeInterFace {
    text: string = "# Hello Editor";

    theme: Theme = "light";

    fileList: FileModel[] = [];

    selectFile: FileModel | null = null;

    isEdit: boolean = false;

    search: string = "";

    isFullscreen: boolean = false;

    async inspectSaveFile(): Promise<boolean> {
        if (this.selectFile && this.selectFile.path) {
            let file_context = await FsUtils.readTextFile(this.selectFile.path);
            if (file_context == this.text) {
                return true;
            } else {
                return false;
            }
        } else if (this.selectFile) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 添加文件
     */
    async add() {
        let result = await this.inspectSaveFile();
        if (!result) {
            result = await this.confirmDialog("文件未保存,是否确认保存?");
            if (result) {
                await this.onSave();
            } else {
                if (this.selectFile && !this.selectFile.path) {
                    let index = this.fileList.findIndex(
                        (item) => item.createTime == this.selectFile?.createTime
                    );
                    if (index != -1) this.fileList.splice(index, 1);
                }
                this.createFile();
            }
        } else {
            this.createFile();
        }
    }

    /**
     * 创建文件
     */
    createFile() {
        let file: FileModel = {
            name: "新建文件.md",
            path: "",
            isDel: false,
            createTime: new Date().toTimeString(),
        };
        this.text = "";
        this.selectFile = file;
        this.isEdit = true;
        this.fileList.push(file);
        return file;
    }

    /**
     * 保存文件
     * @param text 内容
     */
    async onSave() {
        if (this.selectFile?.path) {
            await FsUtils.writeTextFile(this.selectFile?.path, this.text);
        } else {
            let filePath = await FsUtils.getFilePath("");
            if (!filePath) return;
            await FsUtils.writeTextFile(filePath, this.text);
            let index = this.fileList.findIndex(
                (item) => item.createTime == this.selectFile?.createTime
            );
            let list = filePath.split("\\");
            this.fileList[index].path = filePath;
            this.fileList[index].name = list[list.length - 1];
        }
        this.setFileLocalStorage(this.fileList);
    }

    async confirmDialog(message: string) {
        // @ts-ignore
        return confirm(message, {title: "提示", name: "提示", type: "warning"});
    }

    async getFileList(): Promise<FileModel[]> {
        let list = this.getFileLocalStorage();
        for (let i = 0; i < list.length; i++) {
            list[i].isDel = !(await FsUtils.existsFile(list[i].path));
        }
        return list;
    }

    setFileLocalStorage(fileList: FileModel[]) {
        localStorage.setItem("fileUrlList", JSON.stringify(fileList));
    }

    getFileLocalStorage(): FileModel[] {
        let data = localStorage.getItem("fileUrlList");
        return data ? JSON.parse(data) : [];
    }

    async itemClick(file: FileModel) {
        if (file.path == this.selectFile?.path) return;
        let result = await this.inspectSaveFile();
        if (!result) {
            result = await this.confirmDialog(
                this.selectFile?.name + "文件未保存,是否确认保存?"
            );
            if (result) {
                await this.onSave();
            } else {
                if (this.selectFile && !this.selectFile.path) {
                    let index = this.fileList.findIndex(
                        (item) => item.createTime == this.selectFile?.createTime
                    );
                    if (index != -1) this.fileList.splice(index, 1);
                    this.selectFile = null;
                    this.isEdit = false;
                }
            }
        }
        let isDel = await FsUtils.existsFile(file.path);
        if (isDel) {
            this.text = await FsUtils.readTextFile(file.path);
            this.selectFile = file;
            this.isEdit = false;
        } else {
            let index = this.fileList.findIndex((item) => item.path == file.path);
            this.fileList[index].isDel = !isDel;
            let result = await this.confirmDialog(
                "文件已删除，或者文件位置发生改变，是否删除?"
            );
            if (result) {
                this.fileList.splice(index, 1);
                this.setFileLocalStorage(this.fileList);
            }
        }
    }

    async openFile() {
        let flg = await this.inspectSaveFile();
        if (!flg) {
            flg = await this.confirmDialog("文件未保存,是否确认保存?");
            if (flg) {
                await this.onSave();
            } else {
                if (this.selectFile && !this.selectFile.path) {
                    let index = this.fileList.findIndex(
                        (item) => item.createTime == this.selectFile?.createTime
                    );
                    if (index != -1) {
                        this.fileList.splice(index, 1);
                        this.selectFile = null;
                        this.isEdit = false;
                    }
                }
            }
        }
        const urlList = await open({
            multiple: true,
            filters: [
                {
                    name: "md",
                    extensions: ["md"],
                },
            ],
        });
        if (!urlList) return;
        let newFileList: FileModel[] = [];
        for (let i = 0; i < urlList.length; i++) {
            let list = urlList[i].split("\\");
            newFileList.push({
                path: urlList[i],
                name: list[list.length - 1],
                isDel: false,
                createTime: new Date().toTimeString(),
            });
        }
        let newList = newFileList.filter((item) =>
            this.fileList.find((e) => e.path == item.path) ? false : true
        );
        if (newList.length) {
            this.fileList = [...this.fileList, ...newList];
            this.selectFile = newList[newList.length - 1];
            this.text = await FsUtils.readTextFile(this.selectFile.path);
        } else {
            this.selectFile = newFileList[newFileList.length - 1];
            this.text = await FsUtils.readTextFile(this.selectFile.path);
        }
        this.setFileLocalStorage(this.fileList);
        this.isEdit = false;
    }

    handlerFullscreen(): void {
        this.isFullscreen = !this.isFullscreen;
        console.log(this.isFullscreen)
    }


}
